package com.aaa.utils;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

public class UploadUtils {
    public static String upload(MultipartFile myfile, HttpServletRequest request){
        try {
            //1.获取保存文件的路径
            String realPath = request.getSession().getServletContext().getRealPath("/images");
            //2.根据上面的路径创建文件对象
            File file=new File(realPath);
            //3.判断该文件夹是否存在
            if(!file.exists()){
                file.mkdirs();
            }
            //4.获取上传文件的名称. 获取登录者ip+登录者id+登录者的时间戳
            String filename = UUID.randomUUID().toString().replace("-","")+myfile.getOriginalFilename();
            //5.把上传的文件保存到指定服务器下的路径。
            File target=new File(realPath+"/"+filename);
            myfile.transferTo(target);
            System.out.println("上传成功");
            return "/images/"+filename;
        } catch (IOException e) {
            throw new RuntimeException(e); //全局异常处理
        }

    }
    public static String uploadOss(MultipartFile myfile){
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        //   EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        DefaultCredentialProvider defaultCredentialProvider = CredentialsProviderFactory.newDefaultCredentialProvider("LTAI5t9BpBKBJSqbT49tuYU6", "3h1YqFmYOJvWazUo5hxYa10UMLsvxw");
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "qy179";
        // 填写Object完整路径，完整路径中不能包含Bucket名称 上传到oss的bucket中的名称
        String objectName = UUID.randomUUID().toString().replace("-","")+myfile.getOriginalFilename();
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
        // 填写Bucket所在地域。以华东1（杭州）为例，Region填写为cn-hangzhou。
        String region = "cn-beijing";
        // 创建OSSClient实例。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(defaultCredentialProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            InputStream inputStream = myfile.getInputStream();
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            //https://qy179.oss-cn-beijing.aliyuncs.com/2.jpg
            return "http://"+bucketName+"."+endpoint+"/"+objectName;
        } catch (Exception ce) {
//            throw new RuntimeException("上传oss失败");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
}
